package com.ext.aic.utils.http;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

public class UnsafeSSLHelper {
    // 创建信任所有证书的 TrustManager
    private static final TrustManager[] UNTRUSTED_TRUST_MANAGERS = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
            }
    };

    // 创建接受所有主机名的 HostnameVerifier
    private static final HostnameVerifier UNTRUSTED_HOSTNAME_VERIFIER =
            (hostname, session) -> true;

    // 获取不安全的 OkHttpClient 实例
    public static OkHttpClient getUnsafeOkHttpClient() throws Exception {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, UNTRUSTED_TRUST_MANAGERS, new java.security.SecureRandom());

        return new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) UNTRUSTED_TRUST_MANAGERS[0])
                .hostnameVerifier(UNTRUSTED_HOSTNAME_VERIFIER)
                .build();
    }
}
